from django.core.exceptions import ValidationError


import json
import random
from web import models
from django import forms
from django.conf import settings
from utils.alicloud.sms import send_sms
from django_redis import get_redis_connection
from django.core.validators import RegexValidator


class SendSmsForm(forms.Form):
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    phone_regex = r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$'
    mobile_phone = forms.CharField(label='手机号', required=True, error_messages={'required': '手机号不能为空'}, validators=[RegexValidator(phone_regex, '手机号格式错误')])

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data['mobile_phone']

        # 判断短信模板是否有问题
        template = self.request.GET.get('template')
        template_code = settings.TEMPLATE_CODE.get(template)
        if not template_code:
            # 两个方法等价, 但是raise不会继续往下走
            # self.add_error('mobile_phone', '短信模板错误')
            raise ValidationError('短信模板错误')

        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if template == 'register' and exists:
            raise ValidationError('手机号已存在')
        if template == 'login' and not exists:
            raise ValidationError('手机号未注册')

        # 发短信 并且 写入到radis中
        check_code = random.randrange(100000, 999999)
        result = send_sms(mobile_phone, settings.SIGN_NAME, template_code, "{'code': '" + str(check_code) + "'}")
        result = json.loads(str(result, encoding='utf-8'))
        print(result)
        if result['Code'] != 'OK':
            raise ValidationError('短信发送失败, {}'.format(result['Message']))

        # 验证码写入到redis中
        conn = get_redis_connection('default')
        conn.set(mobile_phone, check_code, ex=180)

        return mobile_phone
